﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.DataAnnotations;
using System.Windows.Data;
using MyBet.Class;
using MyBet.Helpers;

namespace MyBet
{
    public partial class PasswordRecovery : ChildWindow
    {
        public PasswordRecovery()
        {
            InitializeComponent();
            LayoutRoot.DataContext = new MyBet.Models.PasswordRecovery();
            AnswerText.Visibility = Visibility.Collapsed;
            QuestionLabel.Visibility = Visibility.Collapsed;
            ResetButton.IsEnabled = false;
            UpdateCulture();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            Error dlg = new Error(LangHelper.GetString("PasswordRecoveryTitle"), LangHelper.GetString("ResetPasswordConfirmation"), Error.ErrorType.Question);
            dlg.Closed += new EventHandler(ResetConfirmation_Closed);
            dlg.Show();
        }

        void ResetConfirmation_Closed(object sender, EventArgs e)
        {
            Error cw = (Error)sender;
            if (cw.DialogResult == true)
            {
                SecurityServiceReference.SecurityServiceClient securitySvc = new SecurityServiceReference.SecurityServiceClient();
                securitySvc.ResetUserPasswordCompleted += new EventHandler<SecurityServiceReference.ResetUserPasswordCompletedEventArgs>(securitySvc_ResetUserPasswordCompleted);
                securitySvc.ResetUserPasswordAsync(LoginText.Text, AnswerText.Text);
                BusyControl.IsBusy = true;
                BusyControl.BusyContent = Helpers.LangHelper.GetString("WaitingPasswordReset");
            }
        }

        void securitySvc_ResetUserPasswordCompleted(object sender, SecurityServiceReference.ResetUserPasswordCompletedEventArgs e)
        {
            BusyControl.IsBusy = false;
            if (e.Result)
            {
                Error passwordResetedDialog = new Error(LangHelper.GetString("PasswordRecoveryTitle"), LangHelper.GetString("PasswordResetOK"),Error.ErrorType.Info);
                passwordResetedDialog.Closed += new EventHandler(passwordResetedDialog_Closed);
                passwordResetedDialog.Show();
            }
            else
            {
                Error passwordResetedDialog = new Error(LangHelper.GetString("PasswordRecoveryTitle"), LangHelper.GetString("PasswordResetKO"), Error.ErrorType.CriticalError);
                passwordResetedDialog.Show();
            }
        }

        void passwordResetedDialog_Closed(object sender, EventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void SetErrorsForControls(DependencyObject parentControl, List<ValidationResult> errorResults) 
        { 
            int childControlCount = VisualTreeHelper.GetChildrenCount(parentControl); 
            for (int i = 0; i < childControlCount; i++) 
            { 
                DependencyObject childControl = VisualTreeHelper.GetChild(parentControl, i); 
                BindingExpression binding = GetBinding(childControl); 
                if (binding == null) { } else 
                { 
                    IEnumerable<ValidationResult> filteredErrorResults = from e in errorResults where e.MemberNames.Contains(binding.ParentBinding.Path.Path) select e; 
                    if (filteredErrorResults.ToList().Count > 0) 
                    { 
                        ValidationResult errorErrorResult = filteredErrorResults.ToList()[0];
                        SetControlError((Control)childControl, Helpers.LangHelper.GetString("MandatoryField")); 
                    } 
                    else 
                    { 
                        ClearControlError((Control)childControl); 
                    } 
                } 
                SetErrorsForControls(childControl, errorResults); 
            } 
        }

        private static BindingExpression GetBinding(DependencyObject childControl)    
        {        
            // ReSharper disable PossibleNullReferenceException        
            BindingExpression binding = null;        
            if (childControl.GetType() == typeof (TextBox))        
            {            
                var txt = childControl as TextBox;            
                binding = txt.GetBindingExpression(TextBox.TextProperty);        
            }        
            else if (childControl.GetType() == typeof (ComboBox))        
            {            
                var cmb = childControl as ComboBox;            
                binding = cmb.GetBindingExpression(Selector.SelectedValueProperty);        
            }        
            else if (childControl.GetType() == typeof (CheckBox))        
            {            
                var chk = childControl as CheckBox;            
                binding = chk.GetBindingExpression(ToggleButton.IsCheckedProperty);        
            }        
            else if (childControl.GetType() == typeof (ListBox))       
            {            
                var lst = childControl as ListBox;            
                binding = lst.GetBindingExpression(Selector.SelectedValueProperty);        
            }        
            // ReSharper restore PossibleNullReferenceException        
            return binding;    
        }     
        
        public void SetControlError(Control control, string errorMessage)    
        {        
            if (control == null) return;        
            var validationHelper =  new ControlValidationHelper(errorMessage);         
            control.SetBinding(TagProperty, new Binding("ValidationError")                                            
            {                                                
                Mode = BindingMode.TwoWay,                                                
                NotifyOnValidationError = true,                                                
                ValidatesOnExceptions = true,                                                
                UpdateSourceTrigger = UpdateSourceTrigger.Explicit,                                                
                Source = validationHelper                                            
            });         
            // this line throws a ValidationException with your custom error message;        
            // the control will catch this exception and switch to its "invalid" state        
            // ReSharper disable PossibleNullReferenceException        
            control.GetBindingExpression(TagProperty).UpdateSource();        
            // ReSharper restore PossibleNullReferenceException    
        }     
        
        public void ClearControlError(Control control)    
        {        
            BindingExpression b = control.GetBindingExpression(TagProperty);         
            if (b != null)        
            {            
                ((ControlValidationHelper) b.DataItem).ThrowValidationError = false;            
                b.UpdateSource();        
            }    
        }

        public bool Validate() 
        {
            List<ValidationResult> validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(LayoutRoot.DataContext, new ValidationContext(LayoutRoot.DataContext, null, null), validationResults, true); 
            //_validationSummary.Errors.Clear();
            SetErrorsForControls(LoginText.Parent, validationResults);
            return validationResults.Count == 0; 
        }

        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                BusyControl.IsBusy = true;
                BusyControl.BusyContent = Helpers.LangHelper.GetString("WaitingLoadQuestionPassword");
                SecurityServiceReference.SecurityServiceClient securitySvc = new SecurityServiceReference.SecurityServiceClient();
                securitySvc.GetPasswordQuestionCompleted += new EventHandler<SecurityServiceReference.GetPasswordQuestionCompletedEventArgs>(securitySvc_GetPasswordQuestionCompleted);
                securitySvc.GetPasswordQuestionAsync(LoginText.Text, EmailText.Text);
            }

        }

        void securitySvc_GetPasswordQuestionCompleted(object sender, SecurityServiceReference.GetPasswordQuestionCompletedEventArgs e)
        {

            BusyControl.IsBusy = false;
            if (!String.IsNullOrEmpty(e.Result))
            {
                AnswerText.Visibility = Visibility.Visible;
                QuestionLabel.Visibility = Visibility.Visible;
                LoginText.IsEnabled = false;
                EmailText.IsEnabled = false;
                LoadButton.IsEnabled = false;
                QuestionLabel.Text = e.Result;
                ResetButton.IsEnabled = true;
            }
            else
            {
                SetControlError(LoginText, Helpers.LangHelper.GetString("WrongLoginEmailErrorMessage"));
                SetControlError(EmailText, Helpers.LangHelper.GetString("WrongLoginEmailErrorMessage"));
            }
        }

        public void UpdateCulture()
        {
            ResetButton.Content = Helpers.LangHelper.GetString("ResetButtonLabel");
            CancelButton.Content = Helpers.LangHelper.GetString("CancelButtonLabel");
            LoginLabel.Text = Helpers.LangHelper.GetString("Login");
            EmailLabel.Text = Helpers.LangHelper.GetString("Email");
            this.Title = Helpers.LangHelper.GetString("PasswordRecoveryTitle");
            LoadButton.Content = Helpers.LangHelper.GetString("LoadPasswordQuestionButton");
        }
    }
}

